import axios from "axios";
import service from "@/config/index";
import Vue from "vue";
import "@/libs/defaults.js";

const $http = axios.create();

const HEADERS = {
  Authorization: "Basic ZGM0ODNlODBhN2EwYmQ5ZWY3MWQ4Y2Y5NzM2NzM5MjQ6MTIzNDU2"
};

function transformLogin (data) {
  let { userAccount, userPassword, userMobile, userCode } = data;
  data = {
    grant_type: userAccount ? "password" : "mobile",
    scope: "all",
    username: userAccount,
    password: userPassword,
    mobile: userMobile,
    code: userCode
  };
  // return $http.post('/auth/oauth/token', {}, {
  //   headers: HEADERS,
  //   params: data
  // })
  return $http({
    method: "post",
    url: `/auth/oauth/token`,
    headers: HEADERS,
    params: data
  })
    .then((response) => {
      return response;
    })
    .catch((error) => {
      if (error.response) {
        if (error.response.status === 401) {
          return Vue.prototype.$message({
            type: "error",
            message: "账号或密码错误"
          });
        } else if (error.response.status === 429) {
          return Vue.prototype.$message({
            type: "error",
            message: "登录过于频繁，请稍后重试"
          });
        } else if (error.response.status === 400) {
          return Vue.prototype.$message({
            type: "error",
            message: "服务器异常"
          });
        }
      }
    });
}

export default {
  getMenuTree () {
    return axios.get(`${service.serviceUser}/menu/tree`);
  },
  getUserInfo () {
    return axios.get(`${service.serviceUser}`);
  },
  updateUserInfo (userInfo) {
    return axios.put(`${service.serviceUser}`, userInfo);
  },
  login (data) {
    // return axios.post('/auth/open/login/v1.0', data)
    // return axios.post('/auth/oauth/token', data)
    return transformLogin(data);
  },
  roleGroup (data) {
    return axios.post(`${service.serviceTenant}/role/search`, data);
  },
  loginCodeSend (data) {
    return axios.post(`${service.serviceUser}/login/code/send`, data);
  },
  codeLogin (data) {
    return axios.post(`${service.serviceUser}/login/code/login`, data);
  },
  dynamicSettings (menuId) {
    return axios.get(`${service.serviceUser}/menu/resource/${menuId} `);
  },
  dynamicSettingsSave (data) {
    return axios.post(`${service.serviceUser}/menu/resource/save`, data);
  },
  // 手机登录图像验证码  /auth/captcha
  phoneLoginCaptcha (data) {
    return axios.get(`/auth/captcha`, data);
  },
  // 手机登录短信 /auth/sms/code
  phoneLoginSmsCode (data) {
    return axios.post(`/auth/sms/code`, data);
  }
};
